#include "TaskCompleteDialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QEventLoop>
#include <QCloseEvent>
#include <QTimer>
#include <QScrollArea>

TaskCompleteDialog::TaskCompleteDialog(const PlanTask& task, QWidget *parent)
    : FramelessWindow(parent)
    , m_task(task)
    , m_taskTitleLabel(new QLabel(this))
    , m_taskInfoLabel(new QLabel(this))
    , m_noteEdit(new QTextEdit(this))
    , m_saveBtn(new QPushButton("保存", this))
    , m_skipBtn(new QPushButton("跳过", this))
    , m_statusCombo(new QComboBox(this))
    , m_dodResultEdit(new QTextEdit(this))
    , m_blockersEdit(new QTextEdit(this))
    , m_artifactsSummaryEdit(new QTextEdit(this))
    , m_artifactsLinksEdit(new QTextEdit(this))
{
    setupUi();

    // 设置窗口为模态
    setWindowModality(Qt::ApplicationModal);

    // 方案B：即使传入了 parent，也强制为顶级窗口/对话框，不随父窗口移动
    setWindowFlags(windowFlags() | Qt::Window | Qt::Dialog | Qt::FramelessWindowHint);
}

TaskCompleteDialog::~TaskCompleteDialog()
{
}

void TaskCompleteDialog::setupUi()
{
    setWindowTitle("任务完成 - 记录过程");
    setMinimumSize(650, 750);  // [FDD-2025-11] 增加高度以容纳新字段
    
    // 创建主背景 widget（修复 FramelessWindow 透明背景问题）
    QWidget* backgroundWidget = new QWidget(this);
    backgroundWidget->setObjectName("backgroundWidget");
    backgroundWidget->setStyleSheet(
        "QWidget#backgroundWidget { "
        "  background-color: #2b2b2b; "
        "  border-radius: 8px; "
        "}"
    );
    
    // 设置深色主题样式
    setStyleSheet(
        "QWidget { "
        "  background-color: transparent; "  // 顶层透明，由 backgroundWidget 提供背景
        "  color: #e0e0e0; "
        "}"
        "QGroupBox { "
        "  color: #e0e0e0; "
        "  border: 1px solid #3c3c3c; "
        "  border-radius: 4px; "
        "  margin-top: 10px; "
        "  padding-top: 10px; "
        "  font-weight: bold; "
        "  background-color: transparent; "
        "}"
        "QGroupBox::title { "
        "  subcontrol-origin: margin; "
        "  subcontrol-position: top left; "
        "  padding: 0 5px; "
        "}"
        "QLabel { "
        "  color: #e0e0e0; "
        "  background-color: transparent; "
        "}"
        "QTextEdit { "
        "  background-color: #3c3c3c; "
        "  border: 2px solid #555; "
        "  border-radius: 5px; "
        "  padding: 10px; "
        "  font-size: 14px; "
        "  color: #e0e0e0; "
        "}"
        "QTextEdit:focus { "
        "  border-color: #4CAF50; "
        "}"
    );
    
    // 创建标题栏
    QWidget* titleBar = new QWidget(backgroundWidget);
    titleBar->setObjectName("titleBar");
    titleBar->setFixedHeight(40);
    titleBar->setStyleSheet(
        "QWidget#titleBar { "
        "  background-color: #1e1e1e; "
        "  border-top-left-radius: 8px; "
        "  border-top-right-radius: 8px; "
        "}"
    );
    
    QHBoxLayout* titleLayout = new QHBoxLayout(titleBar);
    titleLayout->setContentsMargins(15, 0, 15, 0);
    
    QLabel* titleLabel = new QLabel("任务完成 - 记录过程", titleBar);
    titleLabel->setStyleSheet("color: #e0e0e0; font-weight: bold; font-size: 14px; background-color: transparent;");
    titleLayout->addWidget(titleLabel);
    
    titleLayout->addStretch();
    
    // 设置标题栏为可拖拽区域
    setTitlebarWidgets({titleBar, titleLabel});
    
    // backgroundWidget 的布局（包含标题栏和内容）
    QVBoxLayout* backgroundLayout = new QVBoxLayout(backgroundWidget);
    backgroundLayout->setContentsMargins(0, 0, 0, 0);
    backgroundLayout->setSpacing(0);
    backgroundLayout->addWidget(titleBar);
    
    // 顶层容器布局（放置 backgroundWidget）
    QVBoxLayout* containerLayout = new QVBoxLayout(this);
    containerLayout->setContentsMargins(0, 0, 0, 0);
    containerLayout->addWidget(backgroundWidget);
    
    // 内容区域
    QWidget* contentWidget = new QWidget();
    contentWidget->setStyleSheet("background-color: transparent;");
    QVBoxLayout* mainLayout = new QVBoxLayout(contentWidget);
    mainLayout->setSpacing(15);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea(backgroundWidget);
    scrollArea->setWidget(contentWidget);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setFrameShape(QFrame::NoFrame);
    scrollArea->setStyleSheet("QScrollArea { background-color: transparent; border: none; }");

    // 重新设置成员 widget 的父对象（构造函数中默认为 this）
    m_taskTitleLabel->setParent(contentWidget);
    m_taskInfoLabel->setParent(contentWidget);
    m_noteEdit->setParent(contentWidget);
    m_saveBtn->setParent(contentWidget);
    m_skipBtn->setParent(contentWidget);
    m_statusCombo->setParent(contentWidget);
    m_dodResultEdit->setParent(contentWidget);
    m_blockersEdit->setParent(contentWidget);
    m_artifactsSummaryEdit->setParent(contentWidget);
    m_artifactsLinksEdit->setParent(contentWidget);
    
    // ========== 任务信息区 ==========
    QGroupBox* taskInfoGroup = new QGroupBox("任务信息", contentWidget);
    QVBoxLayout* infoLayout = new QVBoxLayout();
    
    // 任务标题
    m_taskTitleLabel->setText(QString("<b style='font-size:16px;'>%1</b>").arg(m_task.getTitle()));
    m_taskTitleLabel->setWordWrap(true);
    
    // 任务时间信息
    QDateTime now = QDateTime::currentDateTime();
    qint64 actualMinutes = m_task.getStartTime().secsTo(now) / 60;
    
    QString timeInfo = QString("开始: %1\n当前: %2\n实际用时: %3 分钟")
        .arg(m_task.getStartTime().toString("yyyy-MM-dd HH:mm"))
        .arg(now.toString("yyyy-MM-dd HH:mm"))
        .arg(actualMinutes);
    
    // 如果预计时间不同于实际时间，显示预计时间
    int plannedMinutes = m_task.getDurationMinutes();
    if (plannedMinutes > 0) {
        timeInfo += QString("\n预计用时: %1 分钟").arg(plannedMinutes);
        
        // 计算差异
        qint64 diff = actualMinutes - plannedMinutes;
        if (diff > 0) {
            timeInfo += QString(" (超出 %1 分钟)").arg(diff);
        } else if (diff < 0) {
            timeInfo += QString(" (提前 %1 分钟)").arg(-diff);
        }
    }
    
    if (!m_task.getDescription().isEmpty()) {
        timeInfo += QString("\n描述: %1").arg(m_task.getDescription());
    }
    
    m_taskInfoLabel->setText(timeInfo);
    m_taskInfoLabel->setStyleSheet("color: #666; font-size: 13px;");
    m_taskInfoLabel->setWordWrap(true);
    
    infoLayout->addWidget(m_taskTitleLabel);
    infoLayout->addWidget(m_taskInfoLabel);
    taskInfoGroup->setLayout(infoLayout);

    mainLayout->addWidget(taskInfoGroup);

    // ========== [FDD-2025-11] 状态选择 ==========
    QHBoxLayout* statusLayout = new QHBoxLayout();
    QLabel* statusLabel = new QLabel("最终状态：", contentWidget);
    statusLabel->setStyleSheet("font-size: 14px; font-weight: bold;");

    m_statusCombo->addItem("✅ 已完成", static_cast<int>(TaskStatus::Done));
    m_statusCombo->addItem("🚧 进行中", static_cast<int>(TaskStatus::Doing));
    m_statusCombo->addItem("⛔ 已阻塞", static_cast<int>(TaskStatus::Blocked));
    m_statusCombo->setCurrentIndex(0);  // 默认"已完成"
    connect(m_statusCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &TaskCompleteDialog::onStatusChanged);

    statusLayout->addWidget(statusLabel);
    statusLayout->addWidget(m_statusCombo);
    statusLayout->addStretch();
    mainLayout->addLayout(statusLayout);

    // ========== [FDD-2025-11] DoD 结果确认 ==========
    QLabel* dodLabel = new QLabel("DoD (完成定义) 结果：", contentWidget);
    dodLabel->setStyleSheet("font-size: 14px; font-weight: bold;");
    mainLayout->addWidget(dodLabel);

    m_dodResultEdit->setPlaceholderText("确认 DoD 是否达成，可以编辑或补充...");
    m_dodResultEdit->setMaximumHeight(100);
    // 加载任务已有的 DoD
    m_dodResultEdit->setPlainText(m_task.getDefinitionOfDone());
    mainLayout->addWidget(m_dodResultEdit);

    // ========== [FDD-2025-11] 阻塞点 & 产出并排 ==========
    QHBoxLayout* blockersArtifactsLayout = new QHBoxLayout();

    // 阻塞点
    QVBoxLayout* blockersLayout = new QVBoxLayout();
    QLabel* blockersLabel = new QLabel("阻塞点：", contentWidget);
    blockersLabel->setStyleSheet("font-size: 14px; font-weight: bold;");
    blockersLayout->addWidget(blockersLabel);

    m_blockersEdit->setPlaceholderText("若仍存在阻塞，请写明...");
    m_blockersEdit->setMaximumHeight(80);
    m_blockersEdit->setPlainText(m_task.getBlockers());
    blockersLayout->addWidget(m_blockersEdit);

    // 产出/证据
    QVBoxLayout* artifactsLayout = new QVBoxLayout();
    QLabel* artifactsLabel = new QLabel("产出/证据：", contentWidget);
    artifactsLabel->setStyleSheet("font-size: 14px; font-weight: bold;");
    artifactsLayout->addWidget(artifactsLabel);

    m_artifactsSummaryEdit->setPlaceholderText("产出概述...");
    m_artifactsSummaryEdit->setMaximumHeight(45);
    TaskArtifacts artifacts = m_task.getArtifacts();
    m_artifactsSummaryEdit->setPlainText(artifacts.summary);
    artifactsLayout->addWidget(m_artifactsSummaryEdit);

    m_artifactsLinksEdit->setPlaceholderText("链接列表（每行一个）：\n- [标题](url)\n- https://...");
    m_artifactsLinksEdit->setMaximumHeight(35);
    m_artifactsLinksEdit->setPlainText(artifacts.evidenceLinks.join("\n"));
    artifactsLayout->addWidget(m_artifactsLinksEdit);

    blockersArtifactsLayout->addLayout(blockersLayout);
    blockersArtifactsLayout->addLayout(artifactsLayout);
    mainLayout->addLayout(blockersArtifactsLayout);
    
    // ========== 完成记录输入区 ==========
    QLabel* noteLabel = new QLabel("完成记录（可选）：", contentWidget);
    noteLabel->setStyleSheet("font-size: 14px; font-weight: bold;");
    mainLayout->addWidget(noteLabel);
    
    // 输入框
    m_noteEdit->setPlaceholderText(
        "请记录任务完成的详细过程、遇到的问题、解决方案、心得体会等...\n\n"
        "例如：\n"
        "• 完成了什么工作\n"
        "• 遇到了哪些问题\n"
        "• 如何解决的\n"
        "• 有什么收获或改进建议"
    );
    m_noteEdit->setMinimumHeight(200);
    mainLayout->addWidget(m_noteEdit);
    
    // 提示信息
    QLabel* hintLabel = new QLabel(
        "💡 提示：记录完成过程有助于回顾和总结，也可以跳过直接完成任务。", 
        contentWidget
    );
    hintLabel->setStyleSheet("color: #999; font-size: 12px;");
    hintLabel->setWordWrap(true);
    mainLayout->addWidget(hintLabel);
    
    // ========== 按钮区 ==========
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_skipBtn);
    buttonLayout->addWidget(m_saveBtn);
    
    // 保存按钮样式
    m_saveBtn->setStyleSheet(
        "QPushButton {"
        "    background-color: #4CAF50;"
        "    color: white;"
        "    border: none;"
        "    padding: 10px 25px;"
        "    border-radius: 5px;"
        "    font-size: 14px;"
        "    min-width: 80px;"
        "}"
        "QPushButton:hover { background-color: #45a049; }"
    );
    
    // 跳过按钮样式
    m_skipBtn->setStyleSheet(
        "QPushButton {"
        "    background-color: #f1f1f1;"
        "    color: #333;"
        "    border: 1px solid #ccc;"
        "    padding: 10px 25px;"
        "    border-radius: 5px;"
        "    font-size: 14px;"
        "    min-width: 80px;"
        "}"
        "QPushButton:hover { background-color: #e0e0e0; }"
    );
    
    mainLayout->addLayout(buttonLayout);

    // 将滚动区域添加到背景容器
    backgroundLayout->addWidget(scrollArea);
    
    // 连接信号
    connect(m_saveBtn, &QPushButton::clicked, this, &TaskCompleteDialog::onSave);
    connect(m_skipBtn, &QPushButton::clicked, this, &TaskCompleteDialog::onSkip);
    
    // 焦点设置到输入框
    m_noteEdit->setFocus();
}

QString TaskCompleteDialog::getCompletionNote() const
{
    return m_completionNote;
}

PlanTask TaskCompleteDialog::getUpdatedTask() const
{
    return m_task;
}

int TaskCompleteDialog::exec()
{
    show();
    raise();
    activateWindow();
    
    QEventLoop eventLoop;
    m_eventLoopStarted = true;
    connect(this, &TaskCompleteDialog::accepted, &eventLoop, &QEventLoop::quit);
    connect(this, &TaskCompleteDialog::rejected, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    
    return m_result;
}

void TaskCompleteDialog::onSave()
{
    m_completionNote = m_noteEdit->toPlainText().trimmed();

    // [FDD-2025-11] 保存所有新字段到任务对象
    // 更新状态
    TaskStatus finalStatus = static_cast<TaskStatus>(m_statusCombo->currentData().toInt());
    m_task.setStatus(finalStatus);

    // 更新 DoD 结果
    m_task.setDefinitionOfDone(m_dodResultEdit->toPlainText().trimmed());

    // 更新阻塞点
    m_task.setBlockers(m_blockersEdit->toPlainText().trimmed());

    // 更新产出/证据
    TaskArtifacts artifacts;
    artifacts.summary = m_artifactsSummaryEdit->toPlainText().trimmed();
    QString linksText = m_artifactsLinksEdit->toPlainText().trimmed();
    if (!linksText.isEmpty()) {
        artifacts.evidenceLinks = linksText.split('\n', Qt::SkipEmptyParts);
    }
    m_task.setArtifacts(artifacts);

    // 保存完成记录
    if (!m_completionNote.isEmpty()) {
        m_task.setCompletionNote(m_completionNote);
    }

    m_result = 1;  // QDialog::Accepted
    emit accepted();
    close();
}

void TaskCompleteDialog::onSkip()
{
    m_completionNote = "";

    // [FDD-2025-11] 即使跳过完成记录，也要保存其他字段
    // 更新状态
    TaskStatus finalStatus = static_cast<TaskStatus>(m_statusCombo->currentData().toInt());
    m_task.setStatus(finalStatus);

    // 更新 DoD 结果
    m_task.setDefinitionOfDone(m_dodResultEdit->toPlainText().trimmed());

    // 更新阻塞点
    m_task.setBlockers(m_blockersEdit->toPlainText().trimmed());

    // 更新产出/证据
    TaskArtifacts artifacts;
    artifacts.summary = m_artifactsSummaryEdit->toPlainText().trimmed();
    QString linksText = m_artifactsLinksEdit->toPlainText().trimmed();
    if (!linksText.isEmpty()) {
        artifacts.evidenceLinks = linksText.split('\n', Qt::SkipEmptyParts);
    }
    m_task.setArtifacts(artifacts);

    m_result = 1;  // QDialog::Accepted (跳过也算接受)
    emit accepted();
    close();
}

void TaskCompleteDialog::onStatusChanged(int index)
{
    // [FDD-2025-11] 状态改变时的处理逻辑
    Q_UNUSED(index);

    TaskStatus newStatus = static_cast<TaskStatus>(m_statusCombo->currentData().toInt());

    // 如果状态改为"已阻塞"，高亮阻塞点输入框
    if (newStatus == TaskStatus::Blocked && m_blockersEdit->toPlainText().trimmed().isEmpty()) {
        m_blockersEdit->setFocus();
        m_blockersEdit->setPlaceholderText("⚠️ 请描述当前的阻塞问题...");
        // 高亮阻塞点输入框（临时边框样式）
        m_blockersEdit->setStyleSheet(
            "QTextEdit { "
            "  background-color: #3c3c3c; "
            "  border: 2px solid #FF9800; "
            "  border-radius: 5px; "
            "  padding: 10px; "
            "  color: #e0e0e0; "
            "}"
        );
        // 1.5 秒后恢复样式
        QTimer::singleShot(1500, this, [this]() {
            m_blockersEdit->setStyleSheet("");
        });
    }
}

